package com.qwc.blog.common.utils;

import com.qwc.blog.entity.vo.TreeSelect;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author qwc
 * @Date 2021/11/1 14:16
 */
public class TreeUtils {
    private TreeUtils() {
        throw new IllegalStateException("Utility class");
    }

    public static List<TreeSelect> buildTree(List<TreeSelect> collect) {
        List<TreeSelect> topNode = new ArrayList<>();
        List<Integer> ids = collect.stream().map(TreeSelect::getId).collect(Collectors.toList());
        for (Iterator<TreeSelect> iterator = collect.iterator(); iterator.hasNext(); ) {
            TreeSelect next = iterator.next();
            if (!ids.contains(next.getPid())) {
                setChildren(next, collect);
                topNode.add(next);
            }
        }
        if (topNode.isEmpty()) {
            topNode.addAll(collect);
        }
        return topNode;
    }

    private static void setChildren(TreeSelect next, List<TreeSelect> collect) {
        List<TreeSelect> children = collect.stream().filter(treeSelect -> next.getId().equals(treeSelect.getPid())).collect(Collectors.toList());
        next.setChildren(children);
        for (TreeSelect child : children) {
            setChildren(child, collect);
        }
    }
}
